package net.java.mediasystems.web.scope;

import java.util.Map;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

/**
 * Custom Spring Scope for the JSF View-Scope.
 */
public class ViewScope implements Scope {

	/**
	 * {@inheritDoc}
	 */
	public Object get(String name, ObjectFactory<?> objectFactory) {
		UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
		
		if (viewRoot != null) {
			Map<String, Object> viewMap = viewRoot.getViewMap();
	
			if (viewMap.containsKey(name)) {
				return viewMap.get(name);
			} else {
				Object object = objectFactory.getObject();
				viewMap.put(name, object);
	
				return object;
			}
		} else {
			return null;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public Object remove(String name) {
		UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
		
		if (viewRoot != null) {
			return viewRoot.getViewMap().remove(name);
		} else {
			return null;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void registerDestructionCallback(String name, Runnable callback) {
		// we do nothing in this method
	}

	/**
	 * {@inheritDoc}
	 */
	public Object resolveContextualObject(String key) {
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	public String getConversationId() {
		return null;
	}
}
